<?php
// +-------------------------------------------------------------------
// | 
// +-------------------------------------------------------------------
// | Copyright (c) 2009-2016 All rights reserved.
// +-------------------------------------------------------------------

// 获取属性类型信息
function get_attribute_type ($type = '')
{
    // TODO 可以加入系统配置
    static $_type = array(
            'num' => array(
                    '数字',
                    'int(10) UNSIGNED NOT NULL'
            ),
            'string' => array(
                    '字符串',
                    'varchar(255) NOT NULL'
            ),
            'textarea' => array(
                    '文本框',
                    'text NOT NULL'
            ),
            'timestamp' => array(
                    '时间戳',
                    'int(10) NOT NULL'
            ),
            'date' => array(
                    '日期',
                    'date NOT NULL'
            ),
            'datetime' => array(
                    '时间',
                    'datetime NOT NULL'
            ),
            'bool' => array(
                    '布尔',
                    'tinyint(2) NOT NULL'
            ),
            'select' => array(
                    '枚举',
                    'char(50) NOT NULL'
            ),
            'radio' => array(
                    '单选',
                    'char(10) NOT NULL'
            ),
            'checkbox' => array(
                    '多选',
                    'varchar(100) NOT NULL'
            ),
            'editor' => array(
                    '编辑器',
                    'text NOT NULL'
            ),
            'picture' => array(
                    '上传图片',
                    'int(10) UNSIGNED NOT NULL'
            ),
            'file' => array(
                    '上传附件',
                    'int(10) UNSIGNED NOT NULL'
            ),
            'callback' => array(
                    '回调',
                    'char(50) NOT NULL'
            )
    );
    return $type ? $_type[$type][0] : $_type;
}

/**
 * 获取对应状态的文字信息
 *
 * @param int $status            
 * @return string 状态文字 ，false 未获取到
 * @author huajie <banhuajie@163.com>
 */
function get_status_title ($status = null)
{
    if (! isset($status))
    {
        return false;
    }
    switch ($status)
    {
        case - 1:
            return '已删除';
            break;
        case 0:
            return '禁用';
            break;
        case 1:
            return '正常';
            break;
        case 2:
            return '待审核';
            break;
        default:
            return false;
            break;
    }
}

/**
 * 获取参数的所有父级分类
 *
 * @param int $cid
 *            分类id
 * @return array 参数分类和父类的信息集合
 * @author huajie <banhuajie@163.com>
 */
function get_parent_category ($cid)
{
    if (empty($cid))
    {
        return false;
    }
    $cates = M('Category')->where(array(
            'status' => 1
    ))->field('id,title,pid')->order('sort')->select();
    $child = get_category($cid); // 获取参数分类的信息
    $pid = $child['pid'];
    $temp = array();
    $res[] = $child;
    while (true)
    {
        foreach ($cates as $key => $cate)
        {
            if ($cate['id'] == $pid)
            {
                $pid = $cate['pid'];
                array_unshift($res, $cate); // 将父分类插入到数组第一个元素前
            }
        }
        if ($pid == 0)
        {
            break;
        }
    }
    return $res;
}

function getTreeSelectArray ($list, $level = 0)
{
    if (! $list)
    {
        return array();
    }
    $array = "";
    $t = count($list);
    $i = 0;
    foreach ($list as $k => $v)
    {
        // $linker = $v['_child'] ? "└" : "├";
        $linker = "├";
        $linker = $t == ++ $i ? "└" : $linker;
        $prefix = str_repeat('　　', $level) . "$linker ";
        $array[$v['id']] = $prefix . $v['title'];
        $_nextArray = getTreeSelectArray($v['_child'], $level + 1);
        foreach ($_nextArray as $kk => $vv)
        {
            $array[$kk] = $vv;
        }
    }
    return $array;
}

function getTableDic ($table, $where = 'status=1', $field = 'id,title', $order = 'id desc')
{
    static $result = array();
    $key = $table . $where . $order;
    if (! isset($result[$key]))
    {
        $r = M($table)->field($field)->where($where)->select();
        $f = explode(',', $field);
        $ra = array();
        foreach ($r as $v)
        {
            $ra[$v[$f[0]]] = $v[$f[1]];
        }
        $result[$key] = $ra;
    }
    return $result[$key];
}

/**
 * 获取错误日志数量
 */
function getErrorCount ()
{
    $cacheKey = "ERROR_LOG_COUNG_" . date('y_m_d');
    $loginfo = S($cacheKey) ?  : [
            'time' => 0,
            'error' => 0,
            'warning' => 0,
            'files' => []
    ];
    
    // 每分钟更新一次
    if ($loginfo['time'] >= time() - 60)
    {
        return $loginfo;
    }
    
    $logPath = "Data/Logs";
    $files = glob($logPath . '/' . date('y_m_d') . '*');
    foreach ($files as $logFile)
    {
        $fp = fopen($logFile, 'r');
        $filekey = md5(fgets($fp));
        isset($loginfo['files'][$filekey]) or $loginfo['files'][$filekey] = 0;
        
        // 检查文件是否更新
        if ($loginfo['time'] < filemtime($logFile))
        {
            fseek($fp, $loginfo['files'][$filekey]);
            while (! feof($fp))
            {
                $line = trim(fgets($fp));
                substr($line, 0, 6) == '[WARN]' and $loginfo['warning'] ++;
                substr($line, 0, 5) == '[ERR]' and $loginfo['error'] ++;
            }
            $loginfo['files'][$filekey] = ftell($fp);
        }
        fclose($fp);
    }
    
    S($cacheKey, $loginfo);
    return $loginfo;
}

/**
 * 获取可用计划任务列表
 */
function getCronList ()
{
    $options = [];
    $crons = glob(APP_PATH . 'Cron/Common/*.class.php') ?  : [];
    foreach ($crons as $file)
    {
        $name = substr(basename($file), 0, - 10);
        $options[$name] = $name;
    }
    $crons = glob(KC_APP_PATH . 'Cron/Common/*.class.php') ?  : [];
    foreach ($crons as $file)
    {
        $name = substr(basename($file), 0, - 10);
        $options[$name] = $name;
    }
    return $options;
}

/**
 * 获取计划任务执行状态
 */
function getCronStatus ($row)
{
    static $cronStatus;
    if (! $cronStatus)
    {
        $cronStatus = o('cron')->status();
    }
    
    // 守护进程执行时所有任务状态默认为 waiting，否则为 stop
    $status = $cronStatus['deamon'] ? "Waiting" : "Stop";
    // 任务禁用时状态默认为 stop
    $row['cron.status'] or $status = "Stop";
    // 通过任务文件锁判断任务真实状态
    isset($cronStatus[$row['cron.name']]) and $status = $cronStatus[$row['cron.name']] ? "Running" : "Error";
    
    return $status;
}

/**
 * 获取计划任务下次执行时间
 */
function getCronTime ($row)
{
    $nextTime = o('cron')->crontime($row['cron.cron']);
    return $nextTime ? date('m-d H:i', $nextTime) : '';
}

/**
 * 导航管理 - 上级分类下拉框
 */
function getChannelOptions ($data = [])
{
    isset($data['id']) and $data['id'] and $where = [
            'id' => [
                    'neq',
                    $data['id']
            ],
            'pid' => [
                    'neq',
                    $data['id']
            ]
    ];
    
    $menu = M('channel')->where($where)->field('id,title,pid')->order('pid,sort')->select();
    return getTreeSelectArray(array(
            array(
                    'id' => 0,
                    'title' => '前台导航',
                    '_child' => list_to_tree($menu)
            )
    ));
}

/**
 * 获取用户角色列表
 */
function getMemberGroup ($uid)
{
    $group = M('auth_group')->alias('a')->join('LEFT JOIN __AUTH_GROUP_ACCESS__ b ON a.id=b.group_id')->where([
            'b.uid' => $uid
    ])->select() ?  : [];
    $groups = [];
    foreach ($group as $v)
    {
        $groups[] = $v['title'];
    }
    return implode(', ', $groups);
}

/**
 * 分类下拉框
 * 编辑分类时, 不显示当前分类和子分类, 防止误操作
 */
function getCategory ($data)
{
    $where = array(
            'status' => 1
    );
    isset($data['id']) and $data['id'] and $where = [
            'pid' => [
                    'neq',
                    $data['id']
            ],
            'id' => [
                    'neq',
                    $data['id']
            ]
    ];
    
    $cate = M('Category')->where($where)->field('id,title,pid')->order('pid,sort')->select();
    
    return getTreeSelectArray(array(
            array(
                    'id' => 0,
                    'title' => '全部分类',
                    '_child' => list_to_tree($cate)
            )
    ));
}

/**
 * 获取分类列表模板文件
 */
function getCategoryListTpl ()
{
    $defaultHomeTheme = C('HOME_DEFAULT_THEME');
    $defaultHomeDepr = C('HOME_TMPL_FILE_DEPR');
    $basePath = APP_PATH . "/" . C('DEFAULT_MODULE') . "/View/" . $defaultHomeTheme . "/Article" . $defaultHomeDepr . "lists*";
    $files = glob($basePath);
    $fileList = array(
            "" => '无'
    );
    foreach ($files as $file)
    {
        $name = str_replace('.html', '', basename($file));
        $fileList[$name] = $name;
    }
    return $fileList;
}

/**
 * 获取分类详情模板文件
 */
function getCategoryDetailTpl ()
{
    $defaultHomeTheme = C('HOME_DEFAULT_THEME');
    $defaultHomeDepr = C('HOME_TMPL_FILE_DEPR');
    $basePath = APP_PATH . "/" . C('DEFAULT_MODULE') . "/View/" . $defaultHomeTheme . "/Article" . $defaultHomeDepr . "detail*";
    $files = glob($basePath);
    $fileList = array(
            "" => '无'
    );
    foreach ($files as $file)
    {
        $name = str_replace('.html', '', basename($file));
        $fileList[$name] = $name;
    }
    return $fileList;
}

/**
 * 文档分类下拉框
 */
function getDocumentCategory ($data)
{
    $category = M('category')->find($data['category_id']);
    $modelId = $category['model'];
    
    $where = array(
            'status' => 1,
            'allow_publish' => 1,
            'is_single' => 0
    );
    
    $cate = M('Category')->where($where)->field('id,title,pid,model,allow_publish')->order('pid,sort')->select();
    
    foreach ($cate as $key => $item)
    {
        // 模型不匹配或不允许发布文章 不得更改到该分类
        if ($data['id'] && $item['model'] != $category['model'] || ! $item['allow_publish'])
        {
            $cate[$key]['title'] = '@' . $item['title'];
        }
    }
    
    return getTreeSelectArray(array(
            array(
                    'id' => 0,
                    'title' => '@全部分类',
                    '_child' => list_to_tree($cate)
            )
    ));
}

/**
 * 广告分类下拉框
 */
function getPosterCategory ()
{
    $config = json_decode(C('POSTER_CATEGORY'), true);
    $category = [];
    foreach ($config as $v)
    {
        $category[$v['category']] = $v['label'];
    }
    return $category;
}